import 'package:flame/flame.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freedom/const/app_content.dart';
import 'package:freedom/webrtc/mircophone_open.dart';
import 'assets_manager_state.dart';

class AssetsManagerCubit extends Cubit<AssetsManagerState> {
  AssetsManagerCubit() : super(const AssetsManagerState.initial());

  /// 加载系统资源
  Future<void> load() async {
    await Future<void>.delayed(const Duration(seconds: 1));
    final allResource = <Function()>[
      // 所有的麻将需要的图
      ...(AppContent.MAHJONG_IMAGES
          .map((e) => () async {
                await Flame.images.load(e);
              })
          .toList()),
      // 麻将声音
      ...(AppContent.MAHJONG_SOUND
          .map((e) => () async {
                await rootBundle.load(e.filePath).then((value) {
                  // 查找具有指定 code 的 SystemAudio 对象的索引
                  int index = AppContent.MAHJONG_SOUND
                      .indexWhere((audio) => audio.code == e.code);
                  if (index != -1) {
                    AppContent.MAHJONG_SOUND[index].audio =
                        value.buffer.asUint8List();
                  }
                });
              })
          .toList()),
      () async {
        MircoPhoneOpen().init();
      }
    ];
    emit(
      state.copyWith(
        assetsCount: allResource.length,
      ),
    );

    late void Function() _triggerLoad;
    _triggerLoad = () async {
      if (allResource.isEmpty) return;
      final loadable = allResource.removeAt(0);
      await loadable();
      _triggerLoad();
      emit(state.copyWith(loaded: state.loaded + 1));
    };

    const _throttleSize = 3;
    for (var i = 0; i < _throttleSize; i++) {
      _triggerLoad();
    }
  }
}
